package com.example.blank700.musicplayer;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.example.blank700.data.Music;
import com.example.blank700.data.MusicList;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    //显示组件
    private ImageButton imgBtn_Previous;
    private ImageButton imgBtn_PlayOrPause;
    private ImageButton imgBtn_Stop;
    private ImageButton imgBtn_Next;
    private ListView list;

    private ArrayList<Music> musicArrayList;

    //当前歌曲的序号，下标从0开始
    private int number = 0;

    // 播放状态
    private int status;

    //广播接收器
    private StatusChangedReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findView();
        registerListeners();
        initMusicList();
        initListView();
        checkMusicfile();

        //绑定广播接收器，可以接收广播
        bindStatusChangedReceiver();

        startService(new Intent(this,MusicService.class));
        status=MusicService.COMMAND_STOP;
    }

    @Override
    protected void onResume() {
        super.onResume();
        sendBroadcastOnCommand(MusicService.COMMAND_CHECK_IS_PLAYING);
    }

    @Override
    protected void onDestroy() {
        if (status==MusicService.STATUS_STOPPED){
            stopService(new Intent(this,MusicService.class));
        }
        super.onDestroy();
    }

    /*获取显示组件*/
    private void findView() {
        imgBtn_Previous = (ImageButton) findViewById(R.id.imageButton1);
        imgBtn_PlayOrPause = (ImageButton) findViewById(R.id.imageButton2);
        imgBtn_Stop = (ImageButton) findViewById(R.id.imageButton3);
        imgBtn_Next = (ImageButton) findViewById(R.id.imageButton4);
        list = (ListView) findViewById(R.id.listView1);
    }

    /*为显示组件注册监听器*/
    private void registerListeners() {
        imgBtn_Previous.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendBroadcastOnCommand(MusicService.COMMAND_PREVIOUS);
            }
        });
        imgBtn_PlayOrPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (status) {
                    case MusicService.STATUS_PLAYING:
                        sendBroadcastOnCommand(MusicService.COMMAND_PAUSE);
                        break;
                    case MusicService.STATUS_PAUSED:
                        sendBroadcastOnCommand(MusicService.COMMAND_RESUME);
                        break;
                    case MusicService.COMMAND_STOP:
                        sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                    default:
                        break;
                }
            }
        });
        imgBtn_Stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendBroadcastOnCommand(MusicService.COMMAND_STOP);
            }
        });
        imgBtn_Next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
            }
        });
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                /*switch (status){
                    case MusicService.STATUS_STOPPED:
                        sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                    case MusicService.STATUS_PLAYING:
                        if (number==position){

                        }else {
                            number=position;
                            sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                        }
                    case MusicService.STATUS_PAUSED:
                        if (number==position){
                            sendBroadcastOnCommand(MusicService.COMMAND_RESUME);
                        }else {
                            number=position;
                            sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                        }
                }*/
                number=position;
                sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
            }
        });
    }

    private void initMusicList() {
        musicArrayList = MusicList.getMusicList();
        if (musicArrayList.isEmpty()) {
            Cursor mMusicCursor = this.getContentResolver().query(
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[]{
                            MediaStore.Audio.Media.TITLE,
                            MediaStore.Audio.Media.DURATION,
                            MediaStore.Audio.Media.ALBUM,
                            MediaStore.Audio.Media.ARTIST,
                            MediaStore.Audio.Media._ID,
                            MediaStore.Audio.Media.DATA,
                            MediaStore.Audio.Media.DISPLAY_NAME
                    }, null, null, MediaStore.Audio.AudioColumns.TITLE);

            if (mMusicCursor != null) {
                //标题
                int indexTitle = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE);
                //艺术家
                int indexArtist = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.ARTIST);
                //路径
                int indexPath = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA);
                //总时长
                int indexTotalTime = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION);

                for (mMusicCursor.moveToFirst(); !mMusicCursor.isAfterLast(); mMusicCursor.moveToNext()) {
                    String strTitle = mMusicCursor.getString(indexTitle);
                    String strArtist = mMusicCursor.getString(indexArtist);
                    String strPath = mMusicCursor.getString(indexPath);
                    String strTotalTime = mMusicCursor.getString(indexTotalTime);
                    if (strArtist.equals("<unknown>"))
                        strArtist = "无艺术家";
                    Music music = new Music(strTitle, strArtist, strPath, strTotalTime);
                    musicArrayList.add(music);
                }
            }
        }
    }

    private void initListView() {
        List<Map<String, String>> list_map = new ArrayList<Map<String, String>>();
        HashMap<String, String> map;
        SimpleAdapter simpleAdapter;
        for (Music music : musicArrayList) {
            map = new HashMap<String, String>();
            map.put("musicName", music.getMusicName());
            map.put("musicArtist", music.getMusicArtist());
            list_map.add(map);
        }

        String[] from = new String[]{"musicName", "musicArtist"};
        int[] to = {R.id.listview_tv_title_item, R.id.listview_tv_artist_item};

        simpleAdapter = new SimpleAdapter(this, list_map, R.layout.listview, from, to);
        list.setAdapter(simpleAdapter);
    }

    private void checkMusicfile() {
        if (musicArrayList.isEmpty()) {
            imgBtn_Previous.setEnabled(false);
            imgBtn_PlayOrPause.setEnabled(false);
            imgBtn_Stop.setEnabled(false);
            imgBtn_Next.setEnabled(false);
            Toast.makeText(getApplicationContext(), "当前没有歌曲文件", Toast.LENGTH_SHORT).show();
        } else {
            imgBtn_Previous.setEnabled(true);
            imgBtn_PlayOrPause.setEnabled(true);
            imgBtn_Stop.setEnabled(true);
            imgBtn_Next.setEnabled(true);
        }
    }

    //绑定广播接收器
    private void bindStatusChangedReceiver(){
        receiver=new StatusChangedReceiver();
        IntentFilter filter=new IntentFilter(MusicService.BROADCAST_MUSICSERVICE_UPDATE_STATUS);
        registerReceiver(receiver,filter);
    }

    //发送命令，控制音乐播放
    private void sendBroadcastOnCommand(int command) {
        Intent intent = new Intent(MusicService.BROADCAST_MUSICSERVICE_CONTROL);
        intent.putExtra("command", command);
        //根据不同命令，封装不同的数据
        switch (command) {
            case MusicService.COMMAND_PLAY:
                intent.putExtra("number", number);
            case MusicService.COMMAND_PREVIOUS:
                break;
            case MusicService.COMMAND_NEXT:
                break;
            case MusicService.COMMAND_PAUSE:
                break;
            case MusicService.COMMAND_STOP:
                break;
            case MusicService.COMMAND_RESUME:
                break;
            default:
                break;
        }
        sendBroadcast(intent);
    }

    //用于播放器状态更新的接收广播
    class StatusChangedReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            //获取播放器状态
            status=intent.getIntExtra("status",-1);
            switch (status){
                case MusicService.STATUS_PLAYING:
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.pause);
                    break;
                case MusicService.STATUS_PAUSED:
                case MusicService.STATUS_STOPPED:
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.play);
                    break;
                case MusicService.STATUS_COMPLETED:
                    sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                    break;
                default:
                    break;
            }
        }
    }
}
